﻿@model ExportProfileModel
@using SmartStore.Core.Domain.DataExchange;
@using SmartStore.Admin.Models.DataExchange;
@{
	var title = string.Concat(T("Common.Profile"), " - ", T("Admin.Common.Edit"));
	ViewBag.Title = title;
}

@using (Html.BeginForm())
{
	<fieldset>
		@Html.HiddenFor(model => model.Id)

		<div class="section-header">
			<div class="title">
				<img src="@Model.Provider.ThumbnailUrl" />
				@title - @Model.Name @Html.ActionLink("(" + T("Admin.Common.BackToList") + ")", "List")
			</div>
			<div class="options">
				@if (Model.HasActiveProvider)
				{
					if (Model.Id != 0)
					{
						<button type="button" id="ProfileExportButton" class="btn btn-primary" data-url="@Url.Action("Execute", "Export", new { area = "Admin", id = Model.Id })">
							<i class="fa fa-cogs"></i>
							<span>@T("Common.Export")</span>
						</button>
					}

					<a href="@Url.Action("Preview", new { id = Model.Id })" class="btn btn-secondary">
						<i class="far fa-eye"></i>
						<span>@T("Admin.Common.Preview")</span>
					</a>
				}
				
				@if (Model.LogFileExists)
				{
					<a href="@Url.Action("DownloadLogFile", new { id = Model.Id })" class="btn btn-secondary" target="LogFile">
						<i class="far fa-file-alt"></i>
						<span>@T("Admin.Configuration.ActivityLog")</span>
					</a>
				}

				<button type="submit" name="save" value="save" class="btn btn-warning">
					<i class="fa fa-check"></i>
					<span>@T("Admin.Common.Save")</span>
				</button>

				<button type="submit" name="save" value="save-continue" class="btn btn-secondary">
					<span>@T("Admin.Common.SaveContinue")</span>
				</button>

				@if (!Model.IsSystemProfile)
				{
					<button type="submit" name="export-profile-delete" id="export-profile-delete" value="export-profile-delete" class="btn btn-danger">
						<i class="far fa-trash-alt"></i>
						<span>@T("Admin.Common.Delete")</span>
					</button>
				}
			</div>
		</div>

		@Html.ValidationSummary(false)

		@Html.SmartStore().TabStrip().Name("export-profile-edit").Style(TabsStyle.Material).Items(x =>
		{
			x.Add().Text(T("Common.General").Text).Content(TabGeneral()).Selected(true);

			if (Model.HasActiveProvider)
			{
				x.Add().Text(T("Common.Partition").Text).Content(TabPartition());
				x.Add().Text(T("Common.Filter").Text).Content(TabFilter());
				x.Add().Text(T("Common.Projection").Text).Content(TabProjection());
				x.Add().Text(T("Admin.Configuration").Text).Content(TabConfiguration());
				x.Add().Text(T("Common.Deployment").Text).Content(TabDeployment());
			}

			EngineContext.Current.Resolve<IEventPublisher>().Publish(new TabStripCreated(x, "export-profile-edit", this.Html, this.Model));
		})
	</fieldset>
}

@helper TabGeneral()
{
	<table class="adminContent">
		<tr>
			<td class="adminTitle">
				@Html.SmartLabelFor(x => x.Name)
			</td>
			<td class="adminData">
				@Html.EditorFor(x => x.Name)
				@Html.ValidationMessageFor(x => x.Name)
			</td>
		</tr>
		<tr>
			<td class="adminTitle">
				@Html.SmartLabelFor(x => x.SystemName)
			</td>
			<td class="adminData">
				<div class="form-control-plaintext">
					@Model.SystemName.NaIfEmpty()
				</div>
			</td>
		</tr>
		<tr>
			<td class="adminTitle">
				@Html.SmartLabelFor(x => x.IsSystemProfile)
			</td>
			<td class="adminData">
				<div class="form-control-plaintext">
					@T(Model.IsSystemProfile ? "Admin.Common.Yes" : "Admin.Common.No")
				</div>
			</td>
		</tr>
		<tr>
			<td class="adminTitle">
				@Html.SmartLabelFor(x => x.Enabled)
			</td>
			<td class="adminData">
				@Html.EditorFor(x => x.Enabled)
				@Html.ValidationMessageFor(x => x.Enabled)
			</td>
		</tr>
        @if (Model.Provider.IsFileBasedExport && Model.Provider.Feature.HasFlag(ExportFeatures.UsesRelatedDataUnits))
        {
		    <tr>
			    <td class="adminTitle">
				    @Html.SmartLabelFor(x => x.ExportRelatedData)
			    </td>
			    <td class="adminData">
				    @Html.EditorFor(x => x.ExportRelatedData)
				    @Html.ValidationMessageFor(x => x.ExportRelatedData)
			    </td>
		    </tr>
        }
		@if (Model.ScheduleTaskId > 0)
		{
			<tr class="mb-5">
				<td class="adminTitle">
					@Html.SmartLabelFor(x => x.ScheduleTaskId)
				</td>
				<td class="adminData">
					@Html.Action("MinimalTask", "ScheduleTask", new { taskId = Model.ScheduleTaskId, returnUrl = Request.RawUrl, cancellable = true, area = "admin" })
				</td>
			</tr>
		}
	</table>
	
	if (Model.HasActiveProvider)
	{
		<table class="adminContent">
			<tr>
				<td class="adminTitle">
					@Html.SmartLabelFor(x => x.Provider.FriendlyName)
				</td>
				<td class="adminData">
					<div class="form-control-plaintext">
						@(Model.Provider.FriendlyName.NaIfEmpty()) (@(Model.ProviderSystemName.NaIfEmpty()))
					</div>
				</td>
			</tr>
			@if (Model.Provider.Description.HasValue())
			{
				<tr>
					<td class="adminTitle">
						@Html.SmartLabelFor(x => x.Provider.Description)
					</td>
					<td class="adminData">
						<div class="form-control-plaintext">
							@Html.Raw(Model.Provider.Description)
						</div>
					</td>
				</tr>
			}
			@if (Model.Provider.Url.HasValue())
			{
				<tr>
					<td class="adminTitle">
						@Html.SmartLabelFor(x => x.Provider.Url)
					</td>
					<td class="adminData">
						<div class="form-control-plaintext">
							<a href="@Model.Provider.Url" target="PluginWebsiteWnd">@Model.Provider.Url</a>
						</div>
					</td>
				</tr>
			}
			@if (Model.Provider.Author.HasValue())
			{
				<tr>
					<td class="adminTitle">
						@Html.SmartLabelFor(x => x.Provider.Author)
					</td>
					<td class="adminData">
						@Html.TextBoxFor(model => model.Provider.Author, new { @readonly = "readonly", @class = "form-control-plaintext" })
					</td>
				</tr>
			}
			@if (Model.Provider.Version.HasValue())
			{
				<tr>
					<td class="adminTitle">
						@Html.SmartLabelFor(x => x.Provider.Version)
					</td>
					<td class="adminData">
						@Html.TextBoxFor(model => model.Provider.Version, new { @readonly = "readonly", @class = "form-control-plaintext" })
					</td>
				</tr>
			}
			<tr>
				<td class="adminTitle">
					@Html.SmartLabelFor(x => x.Provider.EntityTypeName)
				</td>
				<td class="adminData">
					@Html.TextBoxFor(model => model.Provider.EntityTypeName, new { @readonly = "readonly", @class = "form-control-plaintext" })
				</td>
			</tr>
			@if (Model.Provider.FileExtension.HasValue())
			{
				<tr>
					<td class="adminTitle">
						@Html.SmartLabelFor(x => x.Provider.FileExtension)
					</td>
					<td class="adminData">
						<div class="form-control-plaintext">
							@Html.IconForFileExtension(Model.Provider.FileExtension, true)
						</div>
					</td>
				</tr>
			}
		</table>
	}
	else
	{
		<div class="alert alert-warning">
			@T("Admin.Common.ProviderNotLoaded", Model.ProviderSystemName)
		</div>
	}
}

@helper TabPartition()
{
	<div class="alert alert-info alert-dismissible">
		@Html.Raw(T("Admin.DataExchange.Export.Partition.Note"))
		<button type="button" class="close" data-dismiss="alert">&times;</button>
	</div>

	<table class="adminContent">
		<tr>
			<td class="adminTitle">
				@Html.SmartLabelFor(x => x.Offset)
			</td>
			<td class="adminData">
				@Html.EditorFor(x => x.Offset)
				@Html.ValidationMessageFor(x => x.Offset)
			</td>
		</tr>
		<tr>
			<td class="adminTitle">
				@Html.SmartLabelFor(x => x.Limit)
			</td>
			<td class="adminData">
				@Html.EditorFor(x => x.Limit)
				@Html.ValidationMessageFor(x => x.Limit)
			</td>
		</tr>
		<tr>
			<td class="adminTitle">
				@Html.SmartLabelFor(x => x.BatchSize)
			</td>
			<td class="adminData">
				@Html.EditorFor(x => x.BatchSize)
				@Html.ValidationMessageFor(x => x.BatchSize)
			</td>
		</tr>
		<tr>
			<td class="adminTitle">
				@Html.SmartLabelFor(x => x.PerStore)
			</td>
			<td class="adminData">
				@Html.EditorFor(x => x.PerStore)
				@Html.ValidationMessageFor(x => x.PerStore)
			</td>
		</tr>
	</table>
}

@helper TabFilter()
{
	if (Model.Provider.EntityType == ExportEntityType.Product ||
		Model.Provider.EntityType == ExportEntityType.Customer ||
		Model.Provider.EntityType == ExportEntityType.Order || 
		Model.Provider.EntityType == ExportEntityType.NewsLetterSubscription ||
		Model.Provider.EntityType == ExportEntityType.ShoppingCartItem)
	{
		<div class="alert alert-info alert-dismissible">
			@Html.Raw(T("Admin.DataExchange.Export.Filter.Note"))
			<button type="button" class="close" data-dismiss="alert">&times;</button>
			
		</div>
		@Html.Partial("_Tab.Filter", Model)
	}
	else
	{
		<div class="alert alert-info alert-dismissible">
			@T("Admin.DataExchange.Export.NoFiltering")
			<button type="button" class="close" data-dismiss="alert">&times;</button>
		</div>
	}
}

@helper TabProjection()
{
	if (Model.Provider.EntityType == ExportEntityType.Product ||
		Model.Provider.EntityType == ExportEntityType.Order ||
		Model.Provider.EntityType == ExportEntityType.ShoppingCartItem)
	{
		<div class="alert alert-info alert-dismissible">
			@Html.Raw(T("Admin.DataExchange.Export.Projection.Note"))
			<button type="button" class="close" data-dismiss="alert">&times;</button>
		</div>
		@Html.Partial("_Tab.Projection", Model)
	}
	else
	{
		<div class="alert alert-info alert-dismissible">
			@T("Admin.DataExchange.Export.NoProjection")
			<button type="button" class="close" data-dismiss="alert">&times;</button>
		</div>
	}
}

@helper TabConfiguration()
{
	<div id="ProviderConfigurationContainer">
		<fieldset>
			@if (Model.Provider.ConfigPartialViewName.HasValue())
			{
				<div class="alert alert-info alert-dismissible">
					@Html.Raw(T("Admin.DataExchange.Export.Configuration.Note"))
					<button type="button" class="close" data-dismiss="alert">&times;</button>
				</div>
				
				var viewData = new ViewDataDictionary();
				viewData.TemplateInfo.HtmlFieldPrefix = "CustomProperties[ProviderConfigData]";
				viewData.ModelState.Merge(ViewData.ModelState);
				@Html.Hidden("CustomProperties[ProviderConfigData].__Type__", Model.Provider.ConfigDataType.AssemblyQualifiedName)

				try
				{
					@Html.Partial(Model.Provider.ConfigPartialViewName, Model.Provider.ConfigData, viewData)
                }
                catch (Exception ex)
                {
					<div class="alert alert-danger">
						@T("Admin.Configuration.Plugins.UnknownError")
					</div>
					<pre>@ex.ToString()</pre>
				}
			}
			else
			{
				<div class="alert alert-info alert-dismissible">
					@Html.Raw(T("Admin.DataExchange.Export.Configuration.NotRequired", Model.Provider.FriendlyName ?? Model.ProviderSystemName))
					<button type="button" class="close" data-dismiss="alert">&times;</button>
				</div>
			}
		</fieldset>
	</div>
}

@helper TabDeployment()
{
	@Html.Partial("_Tab.Deployment", Model)
}

@Html.DeleteConfirmation("export-profile-delete")

<script type="text/javascript">
	jQuery(document).ready(function () {
		
		// show/hide store projection (cant be done with toggler, because the control is another tab)
		$('#@(Html.FieldIdFor(x => x.PerStore))').change(function () {
			$('#ProjectionStoreContainer').toggle(!$(this).is(':checked'));
		}).trigger('change');

		// show/hide product category filter (cant be done with toggler, because the control is nullable select)
		$('#@(Html.FieldIdFor(x => x.Filter.WithoutCategories))').change(function () {
			$('#FilterCategoryIdsContainer').toggle(_.isEmpty($(this).val()));
		}).trigger('change');

		// show/hide product manufacturer filter (cant be done with toggler, because the control is nullable select)
		$('#@(Html.FieldIdFor(x => x.Filter.WithoutManufacturers))').change(function () {
			$('#FilterManufacturerIdContainer').toggle(_.isEmpty($(this).val()));
		}).trigger('change');

		// show/hide completion email addresses
		$('#@(Html.FieldIdFor(x => x.EmailAccountId))').change(function () {
			$('#CompletedEmailAddressesContainer').toggle(!_.isEmpty($(this).val()));
		}).trigger('change');

		// resolve file name pattern example
		$('#FileNamePatternExampleButton').click(function () {
			var pattern = $('#@(Html.FieldIdFor(x => x.FileNamePattern))').val();
			$(this).doAjax({
				type: 'GET',
				url: '@Url.Action("ResolveFileNamePatternExample", new { id = Model.Id })' + '?pattern=' + encodeURIComponent(pattern),
				callbackSuccess: function (resp) {
					$('#FileNamePatternExample').text(resp);
				}
			});
		});

		// execute export
		$('#ProfileExportButton').click(function (e) {
			e.preventDefault();
			$(this).doPostData({
				ask: @(T("Admin.Common.AskToProceed").JsText)
			});
			return false;
		});
	});
</script>